package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@Api(tags = "文件上传控制器")
@RequestMapping("/v1/file")
public class UpLoadController {
    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public JsonResult upload(MultipartFile file)  {
        String fileName = file.getOriginalFilename();
        log.debug("原始文件名：{}",fileName);
        String fileType = fileName.substring(fileName.lastIndexOf("."));//suffix
        log.debug("文件类型：{}",fileType);
//        fileName = System.currentTimeMillis()+fileType;
        fileName = UUID.randomUUID() +fileType;
        String filePath = "D:/files";
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String filePathDate = sdf.format(new Date());
        log.debug("文件路径时间：{}",filePathDate);
        filePath= filePath + filePathDate;
        log.debug("文件路径完整：{}",filePath);
        // 创建文件夹路径
//        new File(filePath).getParentFile().mkdirs();
        File fileDir = new File(filePath);
        if(!fileDir.exists()){
            //mkdirs()逐层创建mkdir()创建是单创建但是父目录没有会报错
            fileDir.mkdirs();
        }
        File newFile = new File(filePath,fileName);
//        try {
//            newFile.createNewFile();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }


//        try (InputStream inputStream = file.getInputStream();
//             OutputStream outputStream = new FileOutputStream(newFile)) {
//            byte[] buffer = new byte[1024];
//            int bytesRead;
//            while ((bytesRead = inputStream.read(buffer)) != -1) {
//                outputStream.write(buffer, 0, bytesRead);
//            }
//            outputStream.flush();
//        } catch (IOException e) {
//            e.printStackTrace();
//            return new JsonResult(StatusCode.OPERATION_FAILED,"文件上传失败: ");
//        }

        try {
            // 使用transferTo方法,以流的方式写入文件
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return JsonResult.ok(filePathDate+fileName);

    }
}
